from django.shortcuts import render, get_object_or_404
from .models import Post, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_mail
from django.db.models import Count


def post_list(request):
    # posts = Post.published.all()
    object_list = Post.published.all()
    paginator = Paginator(object_list, 2)  # 每页10个帖子
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        #  如果page不是整数，则交付第一页
        posts = paginator.page(1)
    except EmptyPage:
        #  如果页面超出范围，则发送结果的最后一页
        posts = paginator.page(paginator.num_pages)
    return render(request, 'blog/post/list.html', {
        'posts': posts,
        'page': page
    })


def post_detail(request, year, month, day, post):
    # post = get_object_or_404(Post, slug=post, status='draft', publish__month=month)
    # post = get_object_or_404(Post,
    #                          slug=post,
    #                          status='draft',
    #                          publish__month=month,
    #                          publish__day=day,
    #                          publish__year=year)
    post = get_object_or_404(Post,
                             slug=post,
                             publish__month=month,
                             publish__day=day,
                             publish__year=year)
    # List of similar posts
    post_tags_ids = post.tags.values_list('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:2]
    # List of active comments for this post
    comments = post.comments.filter(active=True)
    new_comment = None
    if request.method == 'POST':
        # 发表了一条评论
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # 创建评论对象，但尚未保存到数据库
            new_comment = comment_form.save(commit=False)
            # 将当前帖子分配给评论
            new_comment.post = post
            # 将评论保存到数据库
            new_comment.save()
    else:
        comment_form = CommentForm()
    return render(
        request, 'blog/post/detail.html', {
            'post': post,
            'comments': comments,
            'new_comment': new_comment,
            'comment_form': comment_form,
            'similar_posts': similar_posts,
        })


class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = 'posts'
    paginate_by = 10
    template_name = 'blog/post/list.html'


def post_share(request, post_id):
    # 通过ID检索帖子
    # post = get_object_or_404(Post, id=post_id, status='published')
    post = get_object_or_404(Post, id=post_id)
    sent = False
    if request.method == 'POST':
        # 提交表格
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # Form fields passed validation
            cd = form.cleaned_data
            post_url = request.build_absolute_uri(post.get_absolute_url())
            subject = '{} ({}) recommends you reading "{}"'.format(
                cd['name'], cd['email'], post.title)
            message = 'Read "{}" at {}\n\n{}\'s comments:{}'.format(
                post.title, post_url, cd['name'], cd['comments'])
            send_mail(subject, message, 'yuancj521@163.com', [cd['to']])
            sent = True

    else:
        form = EmailPostForm()
    return render(request, 'blog/post/share.html', {
        'post': post,
        'form': form,
        'sent': sent
    })
